package controllers

import (
	json "encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"novel-test/cache"
	"novel-test/models"
	"path/filepath"
	"time"
)

type NovelController struct {
	beego.Controller
}

func (c *NovelController) Add() {
	img := c.GetString("img")
	title := c.GetString("title")
	author := c.GetString("author")
	types := c.GetString("types")
	content := c.GetString("content")
	if img == "" || title == "" || author == "" || types == "" || content == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "字段为空添加失败",
		}
		c.ServeJSON()
		return
	}
	var novel = models.Novel{
		Img:     img,
		Title:   title,
		Author:  author,
		Types:   types,
		Content: content,
	}
	err := models.DB.Create(&novel).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
		}
		c.ServeJSON()
	}

}
func (c *NovelController) PageList() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)

	offset := (page - 1) * size

	query := models.DB.Model(&models.Novel{})
	var count int64
	query.Count(&count)
	var novel []models.Novel
	query.Offset(offset).Limit(size).Find(&novel)
	data := "data_key"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, data).Result()
	if cacheJson == "" {
		dataJson, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, data, dataJson, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheJson), &novel)
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: novel,
		}
		c.ServeJSON()
	}
}

func (c *NovelController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "文件获取失败",
		}
		c.ServeJSON()
		return
	}
	if header.Size > 5*1024*1024 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "文教不得大于5MB",
		}
		c.ServeJSON()
		return
	}
	ext := filepath.Ext(header.Filename)
	allowExt := map[string]bool{
		".jpg":  true,
		".png":  true,
		".jpeg": true,
	}
	if !allowExt[ext] {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "文件类型错误",
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "上传失败",
		}
		c.ServeJSON()
		return
	} else {
		url := "http://127.0.0.1:8080/" + path
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "上传成功",
			Data: url,
		}
		c.ServeJSON()

	}
}
func (c *NovelController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Novel{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
		}
		c.ServeJSON()
	}

}
